package com.example.micrograss.grass.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.common.core.entity.GrassLike;
import com.example.common.core.utils.UserUtils;
import com.example.common.redis.utils.RedisUtils;
import com.example.micrograss.grass.mapper.GrassLikeMapper;
import com.example.micrograss.grass.service.IGrassLikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class GrassLikeServiceImpl implements IGrassLikeService {

    @Autowired
    private GrassLikeMapper grassLikeMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void like(Integer articleId) {
        Integer uid = UserUtils.getUid();
        /*
         * 点赞逻辑:
         * 1) 当前用户,对这篇文章是否点赞过? =-=> 查
         * 2) 根据结果
         *    有结果,点过赞,这一次就是取消点赞
         *    无结果,没有点过,这次新增一条点赞记录
         * 3) 对与文章本身,记录点赞数+1
         *    借助redis,存储当天的点赞数,而不是直接操作数据库频繁更新+1或者-1
         */

        // 1) 当前用户,对这篇文章是否点赞过? =-=> 查
        GrassLike grassLike = grassLikeMapper.selectOne(Wrappers.
                lambdaQuery(GrassLike.class).
                eq(GrassLike::getUid, uid)
                .eq(GrassLike::getGrassId, articleId));

        // like:num:20251112
        String key = String.format("like:num:%s", DateUtil.format(new Date(),"yyyyMMdd"));
        //  无结果,没有点过,这次新增一条点赞记录
        if (grassLike == null) {
            GrassLike grassLike1 = new GrassLike();
            grassLike1.setUid(uid);
            grassLike1.setGrassId(articleId);
            grassLike1.setCreateTime(new Date());
            grassLike1.setUpdateTime(new Date());
            grassLikeMapper.insert(grassLike1);

            redisUtils.incrCacheMapValue(key,articleId.toString(),1L);
        } else {
            grassLikeMapper.deleteById(grassLike.getId());
            redisUtils.incrCacheMapValue(key,articleId.toString(),-1L);
        }

    }
}